package com.wang;

import java.beans.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BeanExample {
    public static void main(String[] args) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
        // 获取 Person 类的 BeanInfo
        BeanInfo beanInfo = Introspector.getBeanInfo(Person.class);

        // 获取所有属性描述符
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

        // 输出属性信息
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            System.out.println("Property Name: " + propertyDescriptor.getName());
            System.out.println("    Type: " + propertyDescriptor.getPropertyType().getName());
            System.out.println("    Read Method: " + propertyDescriptor.getReadMethod());
            System.out.println("    Write Method: " + propertyDescriptor.getWriteMethod());
            System.out.println("----------------------------");
        }

        // 创建一个 Person 对象
        Person person = new Person();

        // 添加属性变化监听器
        PropertyChangeListener listener = new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                System.out.println("Property changed: " + evt.getPropertyName());
                System.out.println("    Old Value: " + evt.getOldValue());
                System.out.println("    New Value: " + evt.getNewValue());
            }
        };

        // 为 "name" 属性添加监听器
        person.addPropertyChangeListener(listener);
        PropertyDescriptor nameDescriptor = new PropertyDescriptor("name", Person.class);

        // 设置属性值，触发属性变化事件
        nameDescriptor.getWriteMethod().invoke(person, "John Doe");
        Object name = nameDescriptor.getReadMethod().invoke(person);
        System.out.println(name);

        // 输出属性值
        System.out.println("Person Name: " + person.getName());
    }
}
